package com.cn.load.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;



public class Bservlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(new File("E:/chuanzhi/workspace/temp"));
		factory.setSizeThreshold(1024);
		ServletFileUpload upload = new ServletFileUpload(factory);
//		upload.setFileSizeMax(10240);
//		upload.setSizeMax(10240);
		if(!upload.isMultipartContent(request)){
			throw new RuntimeException("当前不是多段式提交!");
		}
		upload.setHeaderEncoding("UTF-8");
		try {
			List<FileItem> list = upload.parseRequest(request);
			for(FileItem fi:list){
				if(fi.isFormField()){
					System.out.println("key:"+fi.getFieldName());
					System.out.println("value1:"+fi.getString());
					System.out.println("value1:"+fi.getString("UTF-8"));
				}else{
					System.out.println("文件提交的键："+fi.getFieldName());
					System.out.println("文件原始名称："+fi.getName());
					System.out.println("文件的mime类型："+fi.getContentType());
					System.out.println("文件长度："+fi.getSize());
					InputStream is = fi.getInputStream();
					FileOutputStream fos = new FileOutputStream("d:/AServlet.jpg");
					IOUtils.copy(is, fos);
					is.close();
					fos.close();
					fi.delete();
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
